<template>
  <div class="page-controller">
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="管理员维护列表"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="formId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      insertable
      delete-id="deleteGroupUsers"
      deletable
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange($event)"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @row-delete="deleteRow"
      @on-cell-select="selectClick"
    >
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, toRaw } from 'vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'

import { apiRequestPost } from '@/api/globalApi.js'
import LocalCache from '@/utils/cache'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiadminMaintquery, apiadminMaintinsert, apiadminMaintdelete, apiUserquery } from '@/api/user'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()
const isTableLoading = ref(false)
const userList = ref([])
// 页面编码
const tableId = 'systemAdmin'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const state = reactive({
  query: {
    current: 1,
    size: 10,
  },
  dataList: [],
})
const userlistCurrent = ref(1)
const loadMoreEnd = ref(false)
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const handleSelect = (item, index) => {
  // tableRef.value.setCellValue(index, 'userName', item.userName)
  for (let v of userList.value) {
    if (item == v.loginName) {
      tableRef.value.setCellValue(index, 'userName', v.userName)
    }
  }
}

const columns: Column[] = reactive([
  {
    label: '用户账号',
    prop: 'loginName',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/rm2/userMaint/query',
        props: { value: 'loginName', label: 'loginName' },
        displayKey: ['loginName', 'userName'],
        searchParam: 'userAName',
      },
    },
  },
  {
    label: '用户名称',
    prop: 'userName',
    align: 'center',
    queryName: '',
    editable: false,
    sortable: false,
    filterable: false,
    readonly: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { formEname: [{ required: true }] },
    },
  },
  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const selectClick = (scope, item) => {
  console.log(scope, item, '查看')
  if (scope.column.property == 'loginName') {
    tableRef.value.setCellValue(scope.$index, 'userName', item.userName)
  }
}
const getUserList = (query) => {
  const par = {
    userAName: query || '',
    current: userlistCurrent.value,
    size: 10,
  }
  // const apiUrl = proxy.$Button_api('query', route.name)
  apiUserquery(par)
    .then((res) => {
      if (res.data.success) {
        // userList.value = [...userList.value, ...res.data.data.result]
        userList.value = userList.value.concat(res.data.data.result)
        // console.log(userList,'userList')
        if (userlistCurrent.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {})
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
      state.query.current = pageConfig.currentPage
    }else{
      pageConfig.currentPage = 1
      state.query.current = 1
    }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiadminMaintquery(state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let userIds = []
  for (let i of checkedRows.value) {
    for (let v of userList.value) {
      if (i.userName == v.userName) {
        userIds.push(v.userId)
      }
    }
  }
  if(!userIds.length){
    useMessage().warning('数据有误，请重新选择')
    return;
  }

  isTableLoading.value = true
  saveSuccessful.value = false
  const apiUrl = proxy.$Button_api('save', route.name)
  apiRequestPost(apiUrl, userIds)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        saveSuccessful.value = true
        ElMessage.success(res.data.message)
        // tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.userId) ids.push(item?.userId)
    })
  isTableLoading.value = true

  const apiUrl = proxy.$Button_api('deleteGroupUsers', route.name)
  apiRequestPost(apiUrl, ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}

const addRowSave = (data) => {
  handleSave()
}
onMounted(() => {
  getUserList('')
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped></style>
